<template>
  <q-page class="container">
    <q-header bordered class="bg-orange text-dark q-py-sm">
      <q-toolbar class="flex justify-between">
        <q-btn icon="arrow_back_ios" flat dense round color="grey-8" @click="$router.back()" />
        <div class="text-h6">提交采购单</div>
        <div></div>
      </q-toolbar>
    </q-header>

    <div class="q-px-md q-pt-md">
      <q-card flat style="border-radius: 15px;">
        <q-card-section>
          <div class="flex justify-between items-center">
            <div class="text-bold text-primary" style="font-size: 16px;">收货信息</div>
            <q-btn label="选择地址" size="sm" dense outline color="grey-8" @click="dialog = true"></q-btn>
          </div>
        </q-card-section>
        <q-card-section>
          <q-form ref="form">
            <q-input dense clearable v-model="delivery.consignee" label="收货人 *" :rules="[val => !!val || '请输入收货人']"></q-input>
            <q-input dense clearable v-model="delivery.tel" label="手机号 *" :rules="[val => !!val || '请输入手机号']"></q-input>
            <q-input dense clearable v-model="delivery.address" autogrow label="收货地址" :rules="[val => !!val || '请输入收货地址']"></q-input>
            <q-input dense clearable v-model="remark" autogrow label="采购单备注"></q-input>
          </q-form>
        </q-card-section>
      </q-card>
    </div>

    <div class="q-pa-md">
      <q-card flat style="border-radius: 15px;">
        <q-card-section>
          <div class="text-bold text-primary" style="font-size: 16px;">采购清单</div>
        </q-card-section>

        <q-card-section>
          <div class="text-bold text-grey-8" style="font-size: 16px;">{{ shopName }}</div>
          <q-separator class="q-my-sm" />
          <settleItem v-for="(item, idx) in list" :key="idx" :item="item" />
        </q-card-section>
      </q-card>
    </div>

    <q-footer class="bg-grey-2 text-dark q-px-md q-py-sm"  v-if="!error">
      <q-toolbar style="border-radius: 25px; padding-right: 0;" class="bg-dark text-white flex justify-between">
        <div class="flex items-end">
          合计：<div class="text-bold" style="font-size: 16px; line-height: normal;">¥<a style="font-size: 30px;">{{ totalMoney[0] }}</a>{{ totalMoney[1] }}</div>
        </div>
        <q-btn label="提交订单" color="orange-4" text-color="dark" size="16px" unelevated padding="0 20px" class="rounded-borders" @click="submitOrder" style="height: 50px; border-radius:0 25px 25px 0;" />
      </q-toolbar>
    </q-footer>

    <q-dialog v-model="dialog" full-width position="bottom">
      <q-card flat class="full-width">
        <q-card-section>
          <div class="text-h6">选择收货地址</div>
        </q-card-section>
        <q-card-section>
          <q-list separator>
            <q-item clickable v-ripple v-for="(item, idx) in (consumer.address || [])" :key="idx" @click="selectAddress(item)">
              <q-item-section>
                <q-item-label>{{ item.consignee }}</q-item-label>
                <q-item-label>{{ item.address }}</q-item-label>
              </q-item-section>

              <q-item-section side top>{{ item.tel }}</q-item-section>
            </q-item>
          </q-list>
        </q-card-section>
      </q-card>
    </q-dialog>
  </q-page>
</template>

<script>
import { defineComponent } from 'vue';
import settleItem from './components/settleItem.vue';

export default defineComponent({
  name: 'shopOrder',
  components: { settleItem },
  data () {
    return {
      delivery: {
        consignee: '',
        tel: '',
        address: ''
      },
      remark: '',

      list: [],
      shopName: '',

      consumer: {},

      dialog: false
    };
  },
  mounted () {
    const shopCarts = this.$q.localStorage.getItem(this.cartId);

    this.list = (shopCarts && shopCarts.carts || []).map(v => ({
      ...v,
      price: Number(v.sale_price),
      amount: v.cart_amount
    }));
    this.shopName = shopCarts && shopCarts.shopName || '';

    this.consumer = this.$q.localStorage.getItem('consumer') || {};
    if (this.consumer && this.consumer.address && this.consumer.address.length > 0) {
      let address = this.consumer.address.find(v => v.default);
      if (!address) {
        address = this.consumer.address[0];
      }

      this.delivery = { ...address };
    } else {
      const delivery = this.$q.localStorage.getItem('delivery') || {};
      if (delivery) {
        this.delivery = { ...delivery };
      }
    }
  },
  methods: {
    splitMoney (money) {
      const arr = String(Number(Number(money).toFixed(2))).split('.');
      if (arr.length === 1) {
        return [arr[0], ''];
      } else {
        return [arr[0], '.' + arr[1]];
      }
    },
    submitOrder () {
      this.$q.localStorage.set('delivery', this.delivery);

      const token = this.$q.localStorage.getItem('consumerToken');
      const shopId = this.$q.localStorage.getItem('myShop');

      const formData = {
        shopId,
        ...this.delivery,
        remark: this.remark,
        detail: this.list.map(v => ({
          material_uid: v.uid,
          amount: v.amount,
          price: v.price,
          remark: ''
        }))
      };

      this.$refs.form.validate().then(ot => {
        if (ot) {
          this.$axios.post('/c/shop/createOrder', { formData }, { headers: { conAuth: token } }).then(({ data }) => {
            if (data.result === 'fail') {
              this.$q.notify({
                message: data.message || '请求失败',
                color: 'negative',
                icon: 'error',
                position: 'center',
                timeout: 4000
              });
            } else {
              this.$q.notify({
                message: '采购单提交成功，可继续采购。',
                color: 'secondary',
                icon: 'done',
                position: 'center',
                timeout: 2000
              });
              this.$q.localStorage.remove(this.cartId);
              this.$router.push({ path: `/shop/${shopId}/list` });
            }
          });
        }
      });
    },
    selectAddress (item) {
      this.delivery = { ...item };
      this.dialog = false;
    }
  },
  computed: {
    cartId () {
      const shopId = this.$q.localStorage.getItem('myShop');
      return `${shopId || ''}_carts`;
    },
    totalMoney () {
      const money = this.list.reduce((a, b) => a + Number(b.price) * Number(b.amount), 0);
      return this.splitMoney(money);
    }
  }
});
</script>

<style lang="scss">

.container {
  position: relative;
  background-color: $grey-2;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 50%; /* 上半部分高度 */
  background: linear-gradient(to bottom, $orange, $grey-2); /* 渐变背景 */
}
</style>
